<?php
namespace app\admin\controller;
use think\Controller;
use auth\Auth;

class Index extends Base
{
    public function index()
    {
        $uid = $this->isLogin();
        //可用权限的id
        $ids= db('auth_group')
                ->alias('a')
                ->join('auth_user_group b','b.group_id = a.id','LEFT')
                ->where('b.uid',$uid)
                ->value('rules');
        $ids = $ids=='all' ? db('auth_rule')->where('is_menu',1)->where('status',1)->column('id') : $ids;
        //有权限的菜单节点
        $rules= db('auth_rule')
                ->field('a.id,a.name,b.name as gname,c.id as cid,c.name as cname,c.icon')
                ->alias('a')
                ->join('auth_rule_group b','b.id = a.rulegroup','LEFT')
                ->join('auth_rule_group c','c.id = b.cid','LEFT')
                ->where('a.id','in',$ids)
                ->where('a.is_menu',1)
                ->where('a.status',1)
                ->order('b.sort')
                ->select();
        //有权限的控制器
        $cname = array_unique(array_column($rules, 'cid'));
        //有权限的菜单
        $menu = array();
        foreach ($cname as $k=>$val){
            foreach ($rules as $v){
                if($val==$v['cid']){
                    $menu[$v['cid']]['cname'] = $v['cname'];
                    $menu[$v['cid']]['icon'] = $v['icon'];
                    $menu[$v['cid']]['group'][] = [
                        'id' => $v['id'],
                        'name' => $v['name'],
                        'gname' => $v['gname']
                    ];
                }
            }
        }
        $this->assign('menu',$menu);
        return $this->fetch();
    }
    
    public function accessDenied()
    {
        return json('无权限访问!');
    }
  
}
